#include "NEC.h"
IrFrame_Def irFrame;
// ================= 接收 NEC 帧 =================
bool NEC_Decode(IrFrame_Def *frame)
{
    if (frame->waveLineNums < (2 + NEC_FRAME_BITS * 2))
        return false;

    // 1.解析到ENC结构中
    return WaveBufferToENCFrame(frame->waveData_un.u16, frame->waveLineNums, &frame->nec);
}

// 将wave解析成enc
bool WaveBufferToENCFrame(const uint16_t *waveBuffer, uint8_t length, NECFrame *frame)
{

    uint32_t data = 0;
    for (uint8_t i = 0; i < NEC_FRAME_BITS; i++)
    {
        uint32_t mark = waveBuffer[2 + i * 2];
        uint32_t space = waveBuffer[3 + i * 2];

        if (!(mark > 400 && mark < 700))
            return false;

        if (space > 1500)
        {
            data |= (1UL << i);
        }
    }

    uint8_t addr = data & 0xFF;
    uint8_t addr_inv = (data >> 8) & 0xFF;
    uint8_t cmd = (data >> 16) & 0xFF;
    uint8_t cmd_inv = (data >> 24) & 0xFF;

    // 标准 NEC
    if ((addr ^ addr_inv) == 0xFF)
    {
        if ((cmd ^ cmd_inv) != 0xFF)
            return false;
        frame->address = addr;
        frame->command = cmd;
        frame->mode = NEC_STANDARD;
        return true;
    }
    else // 扩展 NEC
    {
        if ((cmd ^ cmd_inv) != 0xFF)
            return false;
        frame->address = (uint16_t)addr | ((uint16_t)addr_inv << 8);
        frame->command = cmd;
        frame->mode = NEC_EXTENDED;
        return true;
    }
}

// 协议转换
void UART_Report(IrFrame_Def *frame)
{
    uartProtocolCtrl.frame.cmd = 0x01;
    uartProtocolCtrl.frame.length = frame->waveLineNums * 2;
    for (uint8_t i = 0; i < uartProtocolCtrl.frame.length; i++)
    {
        if (i % 4 == 1)
        {
            uartProtocolCtrl.frame.data[i] = (uint16_t)((frame->waveData_un.u8[i] | 0x80) & 0xFF);
        }
        else
        {
            uartProtocolCtrl.frame.data[i] = (uint16_t)(frame->waveData_un.u8[i] & 0x7F);
        }
    }
    uartProtocolCtrl.frame.checksum = 0; // 不计算校验和
    UART_Protocol_SendFrame(&uartProtocolCtrl, &uartProtocolCtrl.frame);
}

// 协议反转换
// void AntProtocol(IrFrame_Def *frame)
// {
//     uartProtocolCtrl.frame.cmd = 0x01;
//     uartProtocolCtrl.frame.length = frame->waveLineNums * 2;
//     for (uint8_t i = 0; i < uartProtocolCtrl.frame.length; i++)
//     {
//         if (i % 4 == 1)
//         {
//             uartProtocolCtrl.frame.data[i] = (uint16_t)((frame->waveData_un.u8[i] | 0x80) & 0xFF);
//         }
//         else
//         {
//             uartProtocolCtrl.frame.data[i] = (uint16_t)(frame->waveData_un.u8[i] & 0x7F);
//         }
//     }
//     uartProtocolCtrl.frame.checksum = 0; // 不计算校验和
//     UART_Protocol_SendFrame(&uartProtocolCtrl, &uartProtocolCtrl.frame);
// }